import { loginApi } from "@/api"
import { useState } from 'react'
import {
  Form,
  Input,
  Button,
  Toast,
} from 'antd-mobile'
import logo from '@/assets/images/logo.png'
import './login.less'
import { useNavigate } from "react-router-dom"

export default function Login() {
  // 定义 表单需要的数据
  // const [username, setUsername] = useState('12345678901')
  // const [password, setPassword] = useState('wolfcode123')
  const [form, setForm] = useState({ username: "12345678901", password: "wolfcode123" })

  const nav = useNavigate();

  const login = () => {
    loginApi(form).then(res => {
      // 判断是否成功 - errCode 是后端返回的 业务状态码
      if (res?.errCode === 0) {
        //  提示用户
        Toast.show({
          icon: 'success',
          content: '登录成功',
          position: 'top',
        })
        // 把token存储到 本地
        localStorage.setItem('token', res.data);
        // 跳转到 home 页面
        nav('/home')
      }
    })
  }
  // 注册的函数
  const register = () => { }

  const submit = () => {
    isLoginPage ? login() : register();
  }

  const changeUserName = (value: string) => {
    form.username = value;
    setForm(form);
  }
  const changePassword = (value: string) => {
    form.password = value;
    setForm(form);
  }

  // 定义一个开关，控制注册还是登录
  const [isLoginPage, setIsLoginPage] = useState(true)
  return <div className="login">
    <div className="logo">
      <img src={logo} alt="" />
    </div>
    <Form
      onFinish={submit}
      layout='horizontal'
      footer={
        <Button block type='submit' color='primary' size='large'>
          {isLoginPage ? '登录' : '注册'}
        </Button>
      }
      initialValues={form}
    >
      <Form.Item
        name='username'
        rules={[{ required: true, message: '手机号不能为空' }]}
      >
        <Input value={form.username} onChange={changeUserName} placeholder='请输入手机号' />
      </Form.Item>
      <Form.Item name='password' rules={[{ required: true, message: '密码不能为空' }]}>
        <Input value={form.password} type="password" onChange={changePassword} placeholder='请输入密码' />
      </Form.Item>

    </Form>
    <div>
      <Button onClick={() => setIsLoginPage(!isLoginPage)} color='primary' fill='none'>
        去{isLoginPage ? "注册" : '登录'}
      </Button>
    </div>
  </div>
}